package cn.edu.gdu.quizpractice.service.impl;

import cn.edu.gdu.quizpractice.service.ExternalApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 外部API服务实现类
 */
@Service
@Slf4j
public class ExternalApiServiceImpl implements ExternalApiService {
    
    @Autowired
    private RestTemplate restTemplate;
    
    // ONE一个API配置
    @Value("${api.one.key:}")
    private String oneApiKey;
    
    @Value("${api.one.url:https://whyta.cn/api/tx/one}")
    private String oneApiUrl;
    
    // 天气API配置
    @Value("${api.weather.key:}")
    private String weatherApiKey;
    
    @Value("${api.weather.url:}")
    private String weatherApiUrl;
    
    // 新闻API配置
    @Value("${api.news.key:}")
    private String newsApiKey;
    
    @Value("${api.news.url:}")
    private String newsApiUrl;
    
    @Override
    public Map<String, Object> getDailyOne(Integer rand, String date) {
        // 构建请求URL
        StringBuilder urlBuilder = new StringBuilder(oneApiUrl);
        urlBuilder.append("?key=").append(oneApiKey);
        
        if (rand != null) {
            urlBuilder.append("&rand=").append(rand);
        }
        
        if (date != null && !date.isEmpty()) {
            urlBuilder.append("&date=").append(date);
        }
        
        String url = urlBuilder.toString();
        log.info("请求每日一句API: {}", url.replace(oneApiKey, "********"));
        
        // 发送GET请求
        ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
        
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> responseBody = response.getBody();
            
            // 判断API返回是否成功
            if (responseBody != null && responseBody.get("code").equals(200)) {
                return (Map<String, Object>) responseBody.get("result");
            } else {
                String msg = responseBody != null ? responseBody.get("msg").toString() : "未知错误";
                throw new RuntimeException("每日一句API调用失败: " + msg);
            }
        } else {
            throw new RuntimeException("每日一句API请求失败，状态码: " + response.getStatusCodeValue());
        }
    }
    
    @Override
    public Map<String, Object> getWeather(String city) {
        if (weatherApiUrl == null || weatherApiUrl.isEmpty()) {
            throw new RuntimeException("天气API未配置");
        }
        
        // 构建请求URL
        StringBuilder urlBuilder = new StringBuilder(weatherApiUrl);
        urlBuilder.append("?key=").append(weatherApiKey);
        urlBuilder.append("&city=").append(city);
        
        String url = urlBuilder.toString();
        log.info("请求天气API: {}", url.replace(weatherApiKey, "********"));
        
        // 发送请求获取天气数据
        ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
        
        // 解析响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> responseBody = response.getBody();
            // 根据实际API返回格式解析
            // 这里只是一个示例，实际使用时需要根据API文档调整
            return responseBody;
        } else {
            throw new RuntimeException("天气API请求失败，状态码: " + response.getStatusCodeValue());
        }
    }
    
    @Override
    public Map<String, Object> getNews(String type) {
        if (newsApiUrl == null || newsApiUrl.isEmpty()) {
            throw new RuntimeException("新闻API未配置");
        }
        
        // 构建请求URL
        StringBuilder urlBuilder = new StringBuilder(newsApiUrl);
        urlBuilder.append("?key=").append(newsApiKey);
        urlBuilder.append("&type=").append(type);
        
        String url = urlBuilder.toString();
        log.info("请求新闻API: {}", url.replace(newsApiKey, "********"));
        
        // 发送请求获取新闻数据
        ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
        
        // 解析响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> responseBody = response.getBody();
            // 根据实际API返回格式解析
            // 这里只是一个示例，实际使用时需要根据API文档调整
            return responseBody;
        } else {
            throw new RuntimeException("新闻API请求失败，状态码: " + response.getStatusCodeValue());
        }
    }
} 